# -*- coding: utf-8 -*-
"""
    The following copyright and license notice apply only to:
        - those parts of this Turbogears 2 project which are not
          part of the stock quickstarted project
        - those parts which are not otherwise licensed otherwise

    Copyright (C) 2009 Ciaran Farrell <cfarrell1980@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from tg import expose, flash, require, url, request,response, redirect,tmpl_context,validate,config
from pylons.i18n import ugettext as _, lazy_ugettext as l_
#from catwalk.tg2 import Catwalk
from repoze.what import predicates

from lifepyscle.lib.base import BaseController
from lifepyscle.model import DBSession, metadata
from lifepyscle.controllers.error import ErrorController
from lifepyscle import model
from lifepyscle.model import *
from lifepyscle.controllers.secure import SecureController
from lifepyscle.widgets.add_party  import parties_autocomplete_form
from lifepyscle.widgets.quick_autocomplete import parties_single_autocomplete_form
from lifepyscle.widgets import custom_validators
from lifepyscle.widgets.document import doc_form
from lifepyscle.lib.uploader import uploadFile
uploads = config.get('uploads')
cat="document" # added to every returned dict


class DocumentController(BaseController):

    @expose()
    def serve(self,id,**kw):
        """ force download of the file if it exists """
        try:
            D = DBSession.query(Doc).filter(Doc.doc_id==int(id)).one()
        except:
            flash("No document found with id %s"%str(id))
            redirect(url('/record/view/1#documents'))
        else:
            file_to_serve = open(os.path.join(uploads,D.name),'rb')
            transient = file_to_serve.read()
            file_to_serve.close()
            response.headers['Content-Disposition'] = 'attachment; filename="%s"'%(D.orig_name)
            response.headers['Content-Length'] = len(transient) # ie6 over ssl workaround
            response.headers['Pragma'] =  'public'  # ie6 over ssl workaround
            response.headers['Cache-Control'] = 'max-age=0'  # ie6 over ssl workaround
            return transient

    @expose('lifepyscle.templates.view_document')
    def view(self,id=None,**kw):
        if not id:
            flash("No document id provided","warning")
            redirect(url('/record/list')) # why here?
        else:
            try:
                D = DBSession.query(Doc).filter(Doc.doc_id=='%s'%id).one()
            except:
                flash("No document exists with id %s"%id,"warning")
                redirect(url('/record/list')) # why here?
            else:
                tmpl_context.doc_form = doc_form
                return dict(cat=cat,doc=D)

    @expose()
    def delete(self,id=None,**kw):
        try:
            D = DBSession.query(Doc).filter(Doc.doc_id=='%s'%id).one()
        except:
            flash("No document exists with id %d"%id,"error")
        else:
            flash("Got that doc")
        redirect(url('/record/list'))

    @expose()
    #@require(predicates.in_group('cman', msg=l_('Only for contract managers')))
    def do_add(self,**kw):
        R = DBSession.query(Record).filter(Record.record_id==int(kw['record_id'])).one()
        files = request.POST.getall('doc_storage')
        msg = []
        for f in files:
            try:
                x = uploadFile(f)
            except Exception,e:
                msg.append("Could not upload %s: %s"%(f.filename,str(e)))
            else:
                # x is a dictionary with keys file_md5,file_size,file_name
                D = Doc()
                D.name = x['file_name']
                D.orig_name = x['orig_file_name']
                D.size = x['file_size']
                D.md5 = x['file_md5']
                R.docs.append(D)
        if len(msg) == 0:
            flash("Successfully uploaded all files")
        else:
            flash("\n".join(msg))
        redirect(url('/record/view/%s#documents'%kw['record_id']))
